import {
  CTX,
  findChildFormDetails,
  getFormDetailProvider,
  IFormDetailController,
} from '@ibiz-template/runtime';
import { useCtx } from '@ibiz-template/vue3-util';
import { IDEFormDetail } from '@ibiz/model-core';
import { reactive } from 'vue';
import { FormController } from '../../../../form';
import { FormGroupPanelController } from '../../../form-group-panel';
import { FormMDCtrlContentTypeController } from '../../form-mdctrl-content-type.controller';
import { FormMDCtrlItemController } from '../form-mdctrl-repeater-form/form-mdctrl-repeater-form-item.controller';

/**
 * 表单多数据部件表格类型控制器
 *
 * @author zk
 * @date 2023-07-28 08:07:57
 * @export
 * @class FormMDCtrlGridController
 * @extends {EditFormController}
 * @implements {IFormController}
 */
export class FormMDCtrlRepeaterFormOneController extends FormMDCtrlContentTypeController {
  /**
   * 数据
   *
   * @author zk
   * @date 2023-07-31 09:07:25
   * @readonly
   * @type {IData[]}
   * @memberof FormMDCtrlRepeaterFormOneController
   */
  get data(): IData[] {
    return this.parent.state.contentCtrlData as IData[];
  }

  /**
   * 表单项控制器的集合（二维数组）
   *
   * @author zk
   * @date 2023-07-25 05:07:56
   * @type {Array<Array<FormItemController>>}
   * @memberof FormMDCtrlController
   */
  formDetail: Array<{ name: string; c: IFormDetailController }> = [];

  private formCtx!: CTX;

  state: { isInit: boolean } = { isInit: false };

  /**
   * 初始化表单成员控制器
   *
   * @author lxm
   * @date 2022-08-24 21:08:48
   * @protected
   */
  protected async initFormMDCtrlItemControllers(
    details: IDEFormDetail[],
    form: FormController = this.parent.form,
    data: IData = {},
    parent: FormGroupPanelController | undefined = undefined,
  ): Promise<IData> {
    const formData = reactive(data);

    const formController = new FormMDCtrlItemController(
      this.model,
      this.parent.form.context,
      this.parent.form.params,
      this.formCtx,
      formData,
    );
    await formController.onInit();
    formController.evt.on('onFormDataChange', arg => {
      if (arg.data.length > 0) {
        this.onDataItemChange(arg.data[0]);
      }
    });

    formController.state.isLoaded = true;
    await Promise.all(
      details.map(async detail => {
        // 生成表单成员控制器
        const detailProvider = await getFormDetailProvider(detail);
        if (!detailProvider) {
          return;
        }
        form.providers[detail.id!] = detailProvider;
        const detailController = await detailProvider.createController(
          detail,
          formController,
          parent,
        );
        if (!this.formDetail) {
          this.formDetail = [];
        }
        this.formDetail.push({
          name: detail.id!,
          c: detailController,
        });
        // 有子成员的生成子控制器
        const childDetails = findChildFormDetails(detail);
        if (childDetails.length) {
          await this.initFormMDCtrlItemControllers(
            childDetails,
            formController,
            data,
            detailController as FormGroupPanelController,
          );
        }
      }),
    );
    return data;
  }

  /**
   * 初始化formCtx
   *
   * @author zk
   * @date 2023-07-29 05:07:21
   * @memberof FormMDCtrlRepeaterFormController
   */
  useFormMdCtrlCtx(): void {
    this.formCtx = useCtx();
  }

  async initData(): Promise<void> {
    super.initData();
    await this.initFormMDCtrlItemControllers(
      this.model.deformDetails!,
      this.parent.form,
      this.data,
    );
    this.state.isInit = true;
  }

  /**
   * 内部表单项数据发生改变，同步contentCtrlData并设置外部表单值
   *
   * @author zk
   * @date 2023-07-30 05:07:11
   * @param {IData} data
   * @param {number} index
   * @memberof FormMDCtrlController
   */
  onDataItemChange(data: IData): void {
    this.parent.state.contentCtrlData = data;
    this.parent.setFormDataValue();
  }
}
